<script setup lang="ts">
import {computed, ref} from 'vue';
import {useClipboard} from '@vueuse/core';
import {ElIcon, ElMessage, ElTooltip} from 'element-plus';
import {DocumentCopy} from '@element-plus/icons-vue';
import {devCopyProps} from './copy';
import {devDeepMerge, useConfig} from '@/index';

const props = defineProps(devCopyProps);
const emit = defineEmits(['success', 'error']);
const { copy } = useClipboard(); // 获取剪贴板功能
const devCopyRef = ref<HTMLElement | null>(null);

const defaultTooltipProps = useConfig().elTooltipProps;

// 计算最终的 tooltip 配置
const tooltipProps = computed(() =>
    devDeepMerge(defaultTooltipProps, props.elTooltipAttrs, {
      _all: ['visible', 'disabled'],
    })
);

// 将内容复制到剪贴板的逻辑
const getCopyContent = (): string => {
  if (props.onlyCopyText) return props.text || '';
  const content = devCopyRef.value?.innerText || props.text || '';
  return props.removeSpacesOnCopy ? content.replace(/\s+/g, '') : content;
};

const handleCopy = async () => {
  if (props.disabled) return;
  const content = getCopyContent();

  if (!content) {
    console.warn('要复制的内容为空');
    emit('error', '要复制的内容为空');
    return;
  }

  try {
    await copy(content);
    if (props.showMsg) ElMessage.success('复制成功');
    emit('success', content);
  } catch (error) {
    if (props.showMsg) ElMessage.error('复制失败');
    emit('error', error);
  }
};

defineExpose({
  /**
   * 复制内容到剪贴板
   */
  copyContent: handleCopy
});

defineOptions({ name: 'DevCopy' });
</script>

<template>
  <div
      v-if="props.allowIconCopyOnly"
      ref="devCopyRef"
      :style="{ '--hover-color': !props.disabled ? props.hoverColor : '' }"
  >
    <slot />
    <el-tooltip
        :disabled="props.disabled || !props.showTooltip"
        v-bind="tooltipProps"
    >
      <el-icon
          v-if="props.showIcon"
          class="devecoui-copy-box"
          :style="props.iconStyles"
          @click.stop="handleCopy"
      >
        <slot name="icon">
          <DocumentCopy />
        </slot>
      </el-icon>
    </el-tooltip>
  </div>

  <el-tooltip
      v-else
      :disabled="props.disabled || !props.showTooltip"
      v-bind="tooltipProps"
  >
    <div
        ref="devCopyRef"
        class="devecoui-copy-box"
        :style="{ '--hover-color': !props.disabled ? props.hoverColor : '' }"
        @click.stop="handleCopy"
    >
      <slot />
      <el-icon v-if="props.showIcon" :style="props.iconStyles">
        <slot name="icon">
          <DocumentCopy />
        </slot>
      </el-icon>
    </div>
  </el-tooltip>
</template>

<style scoped lang="scss">
.devecoui-copy-box {
  display: inline-block;
  cursor: pointer;
}

.devecoui-copy-box:hover {
  color: var(--hover-color); /* 使用 CSS 变量 */
}
</style>
